package com.yun.zhong.fu.sharecenter.sentinel;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author RenPu
 * @Date 2020/12/30 15:36
 * @Version 1.0
 * @Description: 自定义降级页面的效果或者流控的页面显示效果
 **/

//@Component
public class MyBlockHanderUrl implements UrlBlockHandler {
    @Override
    public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {

        ErrorMsg msg = null;

        if (e instanceof DegradeException) {
            msg = ErrorMsg.builder()
                    .msg("降级了！！")
                    .status(600)
                    .build();
        } else if (e instanceof ParamFlowException) {
            msg = ErrorMsg.builder()
                    .msg("热点参数限流了！！！")
                    .status(601)
                    .build();

        } else if (e instanceof SystemBlockException) {
            msg = ErrorMsg.builder()
                    .msg("系统规则异常！！！")
                    .status(602)
                    .build();

        } else if (e instanceof AuthorityException) {
            msg = ErrorMsg.builder()
                    .msg("授权规则异常！！")
                    .status(603)
                    .build();
        }

        httpServletResponse.setHeader("Content-Type", "application/json;charset=utf-8");
        httpServletResponse.setCharacterEncoding("");
        httpServletResponse.setStatus(500);
        httpServletResponse.setContentType("application/json;charset=utf-8");
        //spring mvc的封装的jkson依赖
        new ObjectMapper().writeValue(
                httpServletResponse.getWriter(),
                msg
        );
    }
}

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
class ErrorMsg {
    private Integer status;
    private String msg;

}